package services;

import assemblers.interfaces.PersonAssembler;
import assemblers.interfaces.PersonInfoAssembler;
import handlers.PersonServiceHandler;
import infos.PersonInfo;
import model.Person;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;

@Path("person")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Local
@Stateless
public class PersonService {

    private PersonAssembler personAssembler;
    private PersonInfoAssembler personInfoAssembler;
    private PersonServiceHandler personServiceHandler;

    @EJB
    public void setPersonInfoAssembler(PersonInfoAssembler personInfoAssembler) {
        this.personInfoAssembler = personInfoAssembler;
    }

    @EJB
    public void setPersonAssembler(PersonAssembler personAssembler) {
        this.personAssembler = personAssembler;
    }

    @EJB(beanName = "PersonServiceHandler")
    public void setPersonServiceHandler(PersonServiceHandler personServiceHandler) {
        this.personServiceHandler = personServiceHandler;
    }

    @GET
    public List<PersonInfo> getPersonList() {
        return personInfoAssembler.assembleList(personServiceHandler.getAllPersons());
    }

    @PUT
    public PersonInfo addPerson(PersonInfo personInfo) {
        Person person = personAssembler.assemble(personInfo);
        person = personServiceHandler.addPerson(person);
        personInfo = personInfoAssembler.assemble(person);
        return personInfo;
    }

    @POST
    public Response alterPerson(PersonInfo person) {
        personServiceHandler.alterPerson(personAssembler.assemble(person));
        return Response.ok().build();
    }

    @DELETE
    @Path("{personId}")
    public Response removePerson(@PathParam("personId")Long id) {
        personServiceHandler.removePerson(id);
        return Response.ok().build();
    }

    @GET
    @Path("full/{personId}")
    public PersonInfo getPerson(@PathParam("personId") Long personId) {
        Person person = personServiceHandler.findPerson(personId);
        return personInfoAssembler.assembleFull(person);
    }

    //TODO
    @GET
    @Path("search/{personNames}")
    public List<PersonInfo> searchByNames(@PathParam("personNames") String personNames){
        return null;
    }

    @GET
    @Path("mail/{email}")
    public boolean ensureUniqueMail(@PathParam("email") String email) {
        return personServiceHandler.ensureUniqueMail(email);
    }

}
